
/**
 * V2.0
 */

var utils=(function(mui){
	
	/**
	 * mui 扩展
	 */
	
	/**
	 * 重写console.log
	 */
	mui.log=function(lg){
		if(!CONFIG) return;
		if(!CONFIG.hasOwnProperty("DEBUG")) return;
		
		if(CONFIG.DEBUG) console.log(lg);
	};
	
	/**
	 * 封装ajax请求
	 */
	mui.ErrorConectTimes=0;//服务连接出错次数
	mui.ConectNetTimes=0;//请求服务次数
	
	///封装的自动重试加载ajax(重要新增：新增备用地址切换功能)
	///第一次请求主服务器，请求失败后检查是否启用灾备服务器配置
	mui.ajax_query = function(func_url, params, onSuccess, onError, retry){
	    var onSuccess = arguments[2]?arguments[2]:function(){};
	    var onError = arguments[3]?arguments[3]:function(){};
	    var retry = arguments[4]?arguments[4]:6;
	    
	    var first_func_url=func_url,otherRoot=arguments[5];
	    
	    //新增第6个参数，设置其根url
	    var rooturl=arguments[5]?arguments[5]:CONFIG.appRootUrl;//服务根目录（需配置）
	    func_url =  rooturl+ func_url;
	    
	    mui.log("["+CONFIG.appName+"]-服务["+func_url+"]第"+retry+"次发送服务器请求");
	    
	    //console.log(retry+':'+func_url);
	    mui.log("["+CONFIG.appName+"]-func_url:"+func_url+"--params:"+JSON.stringify(params));
	    mui.ajax(func_url, {
	        data:params,
	        dataType:'json',
	        type:'get',
	        timeout:3000,
	        success:function(data){
	        	mui.ErrorConectTimes=0;
	        	mui.ConectNetTimes=0;
	        	
	            onSuccess(data);
	        },
	        error:function(xhr,type,errorThrown){
	            retry--;
	            
	            if(mui.ConectNetTimes>3){
	            	return onError(500,'连接服务器失败，请确保网络连接正常');
	            }
	            
	            //整体切换灾备服务器
	            if(plus.storage.getItem('ChangeMainServices')&&
	            plus.storage.getItem('ChangeMainServices')=="true"){
	            mui.log("["+CONFIG.appName+"]-服务["+func_url+"]已切换使用灾备服务器");
	            	mui.ConectNetTimes++;
	            	return mui.ajax_query(first_func_url, params, onSuccess, onError, retry,
	            	CONFIG.appRootBackUrl);
	            }
	            
	            //主服务器
	            if(retry > 3) {
	            	mui.ErrorConectTimes++;
	            	if(mui.ErrorConectTimes>=1&&plus) 
	            		plus.storage.setItem('ChangeMainServices', "true");
	            		
	            	return mui.ajax_query(first_func_url, params, onSuccess, onError, retry,otherRoot);
	            }
	            
	            //主服务器请求失败，切换灾备服务器地址
	            if(retry > 0) {
	            	mui.log("["+CONFIG.appName+"]-服务["+func_url+"]连接失败，开始切换服务器地址...");
	            	
	            	return mui.ajax_query(first_func_url, params, onSuccess, onError, retry,
	            	CONFIG.appRootBackUrl);
	            }
	            	
	            onError(500,'连接服务器失败，请确保网络连接正常');
	            
	        }
	    });
	};
	
	/**
	 * String、Date 扩展
	 */
	//字符串格式化扩展
	String.prototype.format = function(args) {
	if (arguments.length > 0) {
		var result = this;
		if (arguments.length == 1 && typeof (args) == "object") {
			for ( var key in args) {
				var reg = new RegExp("({" + key + "})", "g");
				result = result.replace(reg, args[key]);
			}
		} else {
			for ( var i = 0; i < arguments.length; i++) {
				if (arguments[i] == undefined)
					arguments[i]=" ";
				if (arguments[i] == undefined) {
					return "";
				} else {
					var reg = new RegExp("({[" + i + "]})", "g");
					result = result.replace(reg, arguments[i]);
				}
			}
		}
		return result;
	} else {
		return this;
	}
	}
	
	//日期格式化
	Date.prototype.format =function(format)
    {
        var o = {
        "M+" : this.getMonth()+1, //month
		"d+" : this.getDate(),    //day
		"h+" : this.getHours(),   //hour
		"m+" : this.getMinutes(), //minute
		"s+" : this.getSeconds(), //second
		"q+" : Math.floor((this.getMonth()+3)/3),  //quarter
		"S" : this.getMilliseconds() //millisecond
        }
        if(/(y+)/.test(format)) format=format.replace(RegExp.$1,
        (this.getFullYear()+"").substr(4- RegExp.$1.length));
        for(var k in o)if(new RegExp("("+ k +")").test(format))
        format = format.replace(RegExp.$1,
        RegExp.$1.length==1? o[k] :
        
        
        
        ("00"+ o[k]).substr((""+ o[k]).length));
        return format;
    }
    Date.prototype.addDay=function(days){
		this.setDate(this.getDate() + days);
		return this;
	};
	Date.prototype.addHour=function(hours){
		this.setHours(this.getHours() + hours);
		return this;
	};
	
	/*缓存图片加载*/
	mui.loadCacheFile = function(imgUrl, obj, onLoaded) {
		function getFileSuffix(url) {
			//console.log("url=" + url);
			var index = url.lastIndexOf("/");
			if (index === -1) {
				return null;
			}
			url = url.substring(index);
			index = url.lastIndexOf(".");
			if (index === -1) {
				return null;
			} else {
				return url.substring(index + 1);
			}
		}

		function getLocalFileName(url) {
			var temp = url.substring(url.indexOf("//") + 2, url.lastIndexOf("."));
			temp = temp.replace(/\./g, '_').replace(/\//g, '_');
			temp = temp + url.substring(url.lastIndexOf("."));
			return temp;
		}

		/*不支持的文件格式，不做缓存*/
		/* var suffix  = getFileSuffix(imgUrl);
		 if(null == suffix){
		 		console.log("loadCacheFile file type is not support");
		 		onLoaded({url:imgUrl,obj:obj});
		 		return;
		 }*/

		if (imgUrl.substring(0, 4) != 'http') {
			mui.log("loadCacheFile url must http or https=" + imgUrl);
			onLoaded({
				url: imgUrl,
				obj: obj
			});
			return;
		}

		var localFileName = getLocalFileName(imgUrl);
		var abFilePath = plus.io.convertLocalFileSystemURL("_downloads/" + localFileName);


		plus.io.resolveLocalFileSystemURL("file://" + abFilePath, function(entry) {
			mui.log("file exist="+ abFilePath);
			onLoaded({
				url: abFilePath,
				obj: obj
			});
		}, function(e) {
			//文件不存在 
			//console.log(e.message);
			//console.log("file not exist="+ localFileName + "imgUrl=" +imgUrl);
			var fileName = localFileName;
			var downloader = plus.downloader.createDownload(imgUrl, {
				method: 'GET',
				filename: fileName,
				timeout: 20
			}, function(d, status) {

				if (status == 200) {
					var filePath = plus.io.convertLocalFileSystemURL(d.filename);
					//console.log("download success="+ filePath);
					onLoaded({
						url: filePath,
						obj: obj
					});

				} else {
					onLoaded({
						url: imgUrl,
						obj: obj
					});
				}

			});
			
			downloader.start();
		});
	};
	
	/**
	 * utils 类方法
	 */
	var exports={
		
		//打开新窗口
		openWindow:function(id,url,aniShow,duration,waiting){
			var _extras=arguments[5]?arguments[5]:{},//默认无参数
			zindex=arguments[6]?arguments[6]:10;//默认
			
			return mui.openWindow({
						id: id,
						url: url,
						show:{	
						  autoShow:true,
					      aniShow:aniShow,
					      duration:duration
					    },
					    styles: {
								zindex: zindex					
							},
						waiting: {
							autoShow: waiting,
							title:'正在加载...',
						},
						extras:_extras
			});
		},
		//流应用创建快捷方式
    	CreateShortcut:function(name,icon){
    		if(mui.os.stream) {
				    //最新版本的流基座会自动创建快捷方式；
				    //老版本需要手动上传，故需判断流基座版本号兼容处理
				    var versions = plus.runtime.innerVersion.split('.');
				    if (versions[versions.length - 1] < 21013) {
				        //创建桌面快捷方式
				        if (mui.isFunction(plus.navigator.createShortcut)) {
				            var shortcut = plus.storage.getItem("SHORTCUT");
				            if (!shortcut) {
				                plus.navigator.createShortcut({
				                    name: name,
				                    icon: icon
				                });
				                plus.storage.setItem("SHORTCUT", "true");
				            }
				        }
				    }
			}
    	},
    	/*获取当前网络状态及连接类型*/
		getNetInfo:function(){
			var types = {},info={}; 
			types[0] = "网络连接状态未知"; //0
			types[1] = "未连接网络"; //1
			types[2] = "有线网络"; //2
			types[3] = "无线WIFI网络"; //3
			types[4] = "蜂窝移动2G网络";//4 
			types[5] = "蜂窝移动3G网络"; //5
			types[6] = "蜂窝移动4G网络"; //6
			
			var v=plus.networkinfo.getCurrentType();
			info['type']=plus.networkinfo.getCurrentType();
			info['msg']=types[plus.networkinfo.getCurrentType()];
			
			return info;
		}
		
	};
	
	return exports;
	
})(mui);
